package com.xingdian.xingdianhulianserver.interaptor;

import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 喻敏航
 * @Description:接口拦截器
 * @Date: 19:24  2019/3/8
 **/
public class InterfaceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type","application/json");
        HttpSession session=request.getSession();
        if(session.getAttribute("token")==null){
            Map<String,String> map1 = new HashMap<>();
            map1.put("errorCode","50011");
            map1.put("errorMsg","非法token!");
            String json = JSON.toJSONString(map1);
            PrintWriter writer = response.getWriter();
            writer.print(json);
            writer.close();
            return false;
        }
        int token=(int) session.getAttribute("token")/(210);
        if((token>0&&token<1)||token>=10){
            Map<String,String> map1 = new HashMap<>();
            map1.put("errorCode","50011");
            map1.put("errorMsg","非法token!");
            String json = JSON.toJSONString(map1);
            PrintWriter writer = response.getWriter();
            writer.print(json);
            writer.close();
            return false;
        }
        return true;
    }
}
